package lambda;

import entity.Employee;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**用Collections.sort()  对员工按照年龄排序（年龄一样时用名字排序）
 * */
public class Collections排序 {
    List<Employee> emps = Arrays.asList(
            new Employee(101,"张三",18,256156),
            new Employee(102,"李四",69,464564),
            new Employee(103,"杨九",69,296156),
            new Employee(104,"一下",58,2636156),
            new Employee(105,"田七",78,2896156)
    );

    //用常规的匿名类
    @Test
    public void test1(){
        Collections.sort(emps, new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
                if (o1.getAge() == o2.getAge()) {
                    return o1.getName().compareTo(o2.getName());
                } else {
                    return -Integer.compare(o1.getAge(),o2.getAge());
                }
            }
        });
        for (Employee emp : emps) {
            System.out.println(emp);
        }
    }
    List<Employee> emps2 = Arrays.asList(
            new Employee(101,"张三",18,256156),
            new Employee(102,"李四",69,464564),
            new Employee(103,"杨九",69,296156),
            new Employee(104,"一下",58,2636156),
            new Employee(105,"田七",78,2896156)
    );
    //用Lambda表达式
    @Test
    public void test2(){
        Collections.sort(emps2,(x1,x2) -> {
            if(x1.getAge() == x2.getAge()){
                return  x1.getName().compareTo(x2.getName());
            }else {
                return -Integer.compare(x1.getAge(),x2.getAge());
            }
        });
        for (Employee emp: emps2) {
            System.out.println(emp);
        }
    }
}
